package cn.edu.zstu.qingzhu.qingzhushop.rabbitmq.publisher;

import cn.edu.zstu.qingzhu.qingzhushop.entity.Seckill;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * FileName: SecKillDeadPublisher
 *
 * @Author: LvYibin
 * @Date: 2021/5/17 10:58
 * @Description:
 */
@Component
public class SecKillDeadPublisher {
    private static final Logger log= LoggerFactory.getLogger(SecKillDeadPublisher.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;




    /**
     * 发送消息
     * @param seckill
     */
    public void sendMsg(Seckill seckill){

        try {
            //rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            Long start = seckill.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            if (milliSecond>start){
                throw new Exception("时间参数错误");
            }
            String message = String.valueOf(seckill.getId());
            Message msg = MessageBuilder.withBody(message.getBytes(StandardCharsets.UTF_8)).setDeliveryMode(
                    MessageDeliveryMode.PERSISTENT).build();
            rabbitTemplate.convertAndSend("topic:seckill:exchange1", "routing:key:seckill", msg, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    MessageProperties messageProperties = message.getMessageProperties();
                    //messageProperties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, DeadInfo.class);
//                    System.out.println(milliSecond-start);
                    messageProperties.setExpiration(String.valueOf(start-milliSecond));
                    return message;
                }

            });
            log.info("死信消息模型-生产者-发送消息-订单编号: {} ",message);
        }catch (Exception e){
            log.error("死信消息模型-生产者-发送消息发生异常：{} ",e.fillInStackTrace());
        }

    }
}
